using Lzfy_Refund_Service.Models;
using Lzfy_Refund_Service.Services;
using Microsoft.AspNetCore.Mvc;

namespace Lzfy_Refund_Service.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class PrepayRefundDetailController : ControllerBase
    {
        private readonly IPrepayRefundDetailService _prepayRefundDetailService;
        private readonly ILogger<PrepayRefundDetailController> _logger;

        public PrepayRefundDetailController(
            IPrepayRefundDetailService prepayRefundDetailService,
            ILogger<PrepayRefundDetailController> logger)
        {
            _prepayRefundDetailService = prepayRefundDetailService;
            _logger = logger;
        }

        /// <summary>
        /// 获取线上退费记录列表（分页）
        /// </summary>
        /// <param name="request">查询参数</param>
        /// <returns>线上退费记录列表和总数</returns>
        [HttpPost("query")]
        public async Task<IActionResult> GetPrepayRefundDetailList([FromBody] PrepayRefundDetailQueryRequest request)
        {
            try
            {
                var (records, totalCount) = await _prepayRefundDetailService.GetPrepayRefundDetailListAsync(
                    request.PatientId,
                    request.PatName,
                    request.BalanceSn,
                    request.StartDate,
                    request.EndDate,
                    request.PageIndex,
                    request.PageSize);

                var response = new
                {
                    Records = records.Select(r => new PrepayRefundDetailResponse
                    {
                        BalanceSn = r.BalanceSn,
                        InputDate = r.InputDate,
                        RefundBalance = r.RefundBalance,
                        PatientId = r.PatientId,
                        PatName = r.PatName,
                        RefundTypeName = r.RefundTypeName,
                        AuditDate = r.AuditDate,
                        AcctDate = r.AcctDate,
                        AuditUserId = r.AuditUserId,
                        AuditUserName = r.AuditUserName,
                        BankCardHolder = r.BankCardHolder,
                        AcctId = r.AcctId,
                        RefundBankCity = r.RefundBankCity,
                        PublicAgentRefundBankCity = r.PublicAgentRefundBankCity,
                        Status = GetRefundStatus(r)
                    }).ToList(),
                    TotalCount = totalCount,
                    PageIndex = request.PageIndex,
                    PageSize = request.PageSize,
                    TotalPages = (int)Math.Ceiling(totalCount / (double)request.PageSize)
                };

                return Ok(response);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取线上退费记录列表失败");
                return StatusCode(500, "获取线上退费记录列表失败：" + ex.Message);
            }
        }

        /// <summary>
        /// 根据退费流水号获取线上退费记录
        /// </summary>
        /// <param name="balanceSn">退费流水号</param>
        /// <returns>线上退费记录</returns>
        [HttpPost("detail")]
        public async Task<IActionResult> GetPrepayRefundDetail([FromBody] string balanceSn)
        {
            try
            {
                var record = await _prepayRefundDetailService.GetPrepayRefundDetailByBalanceSnAsync(balanceSn);
                if (record == null)
                {
                    return NotFound($"未找到退费流水号为 {balanceSn} 的记录");
                }

                var response = new PrepayRefundDetailResponse
                {
                    BalanceSn = record.BalanceSn,
                    InputDate = record.InputDate,
                    RefundBalance = record.RefundBalance,
                    PatientId = record.PatientId,
                    PatName = record.PatName,
                    RefundTypeName = record.RefundTypeName,
                    AuditDate = record.AuditDate,
                    AcctDate = record.AcctDate,
                    AuditUserId = record.AuditUserId,
                    AuditUserName = record.AuditUserName,
                    BankCardHolder = record.BankCardHolder,
                    AcctId = record.AcctId,
                    RefundBankCity = record.RefundBankCity,
                    PublicAgentRefundBankCity = record.PublicAgentRefundBankCity,
                    Status = GetRefundStatus(record)
                };

                return Ok(response);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取线上退费记录详情失败");
                return StatusCode(500, "获取线上退费记录详情失败：" + ex.Message);
            }
        }

        /// <summary>
        /// 根据患者ID获取线上退费记录列表
        /// </summary>
        /// <param name="patientId">患者ID</param>
        /// <returns>线上退费记录列表</returns>
        [HttpPost("patient")]
        public async Task<IActionResult> GetPrepayRefundDetailsByPatientId([FromBody] string patientId)
        {
            try
            {
                var records = await _prepayRefundDetailService.GetPrepayRefundDetailsByPatientIdAsync(patientId);

                var response = records.Select(r => new PrepayRefundDetailResponse
                {
                    BalanceSn = r.BalanceSn,
                    InputDate = r.InputDate,
                    RefundBalance = r.RefundBalance,
                    PatientId = r.PatientId,
                    PatName = r.PatName,
                    RefundTypeName = r.RefundTypeName,
                    AuditDate = r.AuditDate,
                    AcctDate = r.AcctDate,
                    AuditUserId = r.AuditUserId,
                    AuditUserName = r.AuditUserName,
                    BankCardHolder = r.BankCardHolder,
                    AcctId = r.AcctId,
                    RefundBankCity = r.RefundBankCity,
                    PublicAgentRefundBankCity = r.PublicAgentRefundBankCity,
                    Status = GetRefundStatus(r)
                }).ToList();

                return Ok(response);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取患者线上退费记录列表失败");
                return StatusCode(500, "获取患者线上退费记录列表失败：" + ex.Message);
            }
        }

        /// <summary>
        /// 创建线上退费记录
        /// </summary>
        /// <param name="request">创建请求</param>
        /// <returns>创建结果</returns>
        [HttpPost("create")]
        public async Task<IActionResult> CreatePrepayRefundDetail([FromBody] PrepayRefundDetailCreateRequest request)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }

                var result = await _prepayRefundDetailService.CreatePrepayRefundDetailAsync(request);
                if (result)
                {
                    return Ok(new { Success = true, Message = "创建线上退费记录成功" });
                }
                else
                {
                    return BadRequest(new { Success = false, Message = "创建线上退费记录失败，可能是退费流水号已存在" });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建线上退费记录失败");
                return StatusCode(500, "创建线上退费记录失败：" + ex.Message);
            }
        }

        /// <summary>
        /// 更新线上退费记录
        /// </summary>
        /// <param name="request">更新请求</param>
        /// <returns>更新结果</returns>
        [HttpPost("update")]
        public async Task<IActionResult> UpdatePrepayRefundDetail([FromBody] PrepayRefundDetailUpdateRequest request)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }

                var result = await _prepayRefundDetailService.UpdatePrepayRefundDetailAsync(request);
                if (result)
                {
                    return Ok(new { Success = true, Message = "更新线上退费记录成功" });
                }
                else
                {
                    return BadRequest(new { Success = false, Message = "更新线上退费记录失败，可能是退费流水号不存在或记录已审核" });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新线上退费记录失败");
                return StatusCode(500, "更新线上退费记录失败：" + ex.Message);
            }
        }

        /// <summary>
        /// 删除线上退费记录
        /// </summary>
        /// <param name="balanceSn">退费流水号</param>
        /// <returns>删除结果</returns>
        [HttpPost("delete")]
        public async Task<IActionResult> DeletePrepayRefundDetail([FromBody] string balanceSn)
        {
            try
            {
                var result = await _prepayRefundDetailService.DeletePrepayRefundDetailAsync(balanceSn);
                if (result)
                {
                    return Ok(new { Success = true, Message = "删除线上退费记录成功" });
                }
                else
                {
                    return BadRequest(new { Success = false, Message = "删除线上退费记录失败，可能是退费流水号不存在或记录已审核" });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除线上退费记录失败");
                return StatusCode(500, "删除线上退费记录失败：" + ex.Message);
            }
        }

        /// <summary>
        /// 审核线上退费记录
        /// </summary>
        /// <param name="request">审核请求</param>
        /// <returns>审核结果</returns>
        [HttpPost("audit")]
        public async Task<IActionResult> AuditPrepayRefundDetail([FromBody] PrepayRefundDetailAuditRequest request)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }

                var result = await _prepayRefundDetailService.AuditPrepayRefundDetailAsync(request);
                if (result)
                {
                    return Ok(new { Success = true, Message = "审核线上退费记录成功" });
                }
                else
                {
                    return BadRequest(new { Success = false, Message = "审核线上退费记录失败，可能是退费流水号不存在或记录已审核" });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "审核线上退费记录失败");
                return StatusCode(500, "审核线上退费记录失败：" + ex.Message);
            }
        }

        /// <summary>
        /// 结算线上退费记录
        /// </summary>
        /// <param name="balanceSn">退费流水号</param>
        /// <returns>结算结果</returns>
        [HttpPost("settle")]
        public async Task<IActionResult> SettlePrepayRefundDetail([FromBody] string balanceSn)
        {
            try
            {
                var result = await _prepayRefundDetailService.SettlePrepayRefundDetailAsync(balanceSn);
                if (result)
                {
                    return Ok(new { Success = true, Message = "结算线上退费记录成功" });
                }
                else
                {
                    return BadRequest(new { Success = false, Message = "结算线上退费记录失败，可能是退费流水号不存在、记录未审核或已结算" });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "结算线上退费记录失败");
                return StatusCode(500, "结算线上退费记录失败：" + ex.Message);
            }
        }

        /// <summary>
        /// 获取退费记录状态
        /// </summary>
        private string GetRefundStatus(PrepayRefundDetail record)
        {
            if (record.AcctDate.HasValue)
            {
                return "已结算";
            }
            else if (record.AuditDate.HasValue)
            {
                return "已审核";
            }
            else
            {
                return "待审核";
            }
        }
    }
}